<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="机主名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入机主名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份" prop="UIdentity">
        <el-select v-model="queryParams.UIdentity" placeholder="请选择身份" clearable style="width: 200px">
          <el-option
              v-for="dict in wxz_order_identity"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学号" prop="studentId">
        <el-input
            v-model="queryParams.studentId"
            placeholder="请输入学号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="宿舍栋数" prop="building">
        <el-select v-model="queryParams.building" placeholder="请选择宿舍栋数" clearable style="width: 200px">
          <el-option
              v-for="dict in wxz_order_building"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="宿舍号" prop="dormitory">
        <el-input
            v-model="queryParams.dormitory"
            placeholder="请输入宿舍号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
            v-model="queryParams.phone"
            placeholder="请输入手机号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择订单类型" clearable style="width: 200px">
          <el-option
              v-for="dict in wxz_order_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单详情" prop="details">
        <el-input
            v-model="queryParams.details"
            placeholder="请输入订单详情"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="维修人员" prop="nickName">
        <el-input
            v-model="queryParams.nickName"
            placeholder="请输入维修人员"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="完成订单" prop="completionTimeRange">
        <el-date-picker
            clearable
            v-model="queryParams.completionTimeRange"
            type="datetimerange"
            value-format="YYYY-MM-DD hh:mm:ss"
            date-format="YYYY/MM/DD ddd"
            time-format=" hh:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['wxz:order:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['wxz:order:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['wxz:order:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            color="#626aef"
            plain
            icon="Download"
            @click="handleExportByDate"
            v-hasPermi="['wxz:order:export']"
        >导出已选日期义劳
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['wxz:order:export']"
        >导出全部
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Warning"
            @click="handleResetSemester"
            v-hasPermi="['wxz:order:remove']"
        >学期大清空
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table stripe v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--<el-table-column label="序号" type="index" width="55" align="center"/>-->
      <el-table-column label="机主名称" align="center" width="80" prop="name"/>
      <el-table-column label="身份" align="center" width="65" prop="UIdentity">
        <template #default="scope">
          <dict-tag :options="wxz_order_identity" :value="scope.row.UIdentity"/>
        </template>
      </el-table-column>
      <el-table-column label="宿舍地址" align="center" prop="building">
        <template #default="scope">
          {{ scope.row.building }}#{{ scope.row.dormitory }}
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" width="110" prop="phone"/>
      <!--<el-table-column label="订单类型" align="center" width="80" prop="type">
        <template #default="scope">
          <dict-tag :options="wxz_order_type" :value="scope.row.type"/>
        </template>
      </el-table-column>-->
      <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wxz_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="维修人员" align="center" width="80" prop="nickName"/>
      <el-table-column label="照片" align="center" prop="isUploads">
        <template #default="scope">
          <el-tag v-if="scope.row.isUploads == 1" type="success">
            已上传
          </el-tag>
          <el-tag v-else type="primary">
            未上传
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="详情" align="center" prop="details">
        <template #default="{ row }">
          <span class="table-details">{{ row.details }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成订单时间" align="center" prop="completionTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.completionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary"
                       icon="Edit"
                       @click="handleUpdate(scope.row)"
                       v-hasPermi="['wxz:order:edit']">
            </el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['wxz:now:remove']">
            </el-button>
          </el-tooltip>
          <el-tooltip content="作废" placement="top">
            <el-button link type="primary" icon="CircleClose" @click="handleInvalidate(scope.row)"
                       v-hasPermi="['wxz:order:mark-invalid']">
            </el-button>
          </el-tooltip>

          <el-tooltip content="更多" placement="top">
            <el-button link type="primary" icon="More" @click="handleOrderDesc(scope.row)"
                       v-hasPermi="['wxz:order:detail']">
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改维修站订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="机主名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入机主名称"/>
        </el-form-item>
        <el-form-item label="身份" prop="UIdentity">
          <el-radio-group v-model="form.UIdentity">
            <el-radio
                v-for="dict in wxz_order_identity"
                :key="dict.value"
                :label="+dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学号"/>
        </el-form-item>
        <el-form-item label="宿舍栋数" prop="building">
          <el-select v-model="form.building" placeholder="请选择宿舍栋数">
            <el-option
                v-for="dict in wxz_order_building"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="宿舍号" prop="dormitory">
          <el-input v-model="form.dormitory" placeholder="请输入宿舍号"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="订单类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择订单类型">
            <el-option
                v-for="dict in wxz_order_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单详情" prop="details">
          <el-input v-model="form.details" type="textarea" placeholder="请输入订单详情"/>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="form.status"
                     :disabled="form.id == null"
                     placeholder="请选择订单状态">
            <el-option
                v-for="dict in wxz_order_status"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Now">
import {listOrder, getOrder, delOrder, addOrder, updateOrder, invalidateOrder, resetSemester} from "@/api/wxz/order.js";
import {userOrderState} from "@/store/index.js"

const orderState = userOrderState();

const router = useRouter()
const {proxy} = getCurrentInstance();
const {
  wxz_order_type,
  wxz_order_identity,
  wxz_order_status,
  wxz_order_building
} = proxy.useDict('wxz_order_type', 'wxz_order_identity', 'wxz_order_status', 'wxz_order_building');

const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    UIdentity: null,
    studentId: null,
    building: null,
    dormitory: null,
    phone: null,
    type: null,
    details: null,
    status: null,
    staffId: null,
    completionTimeRange: null,
    assignorId: null,
  },
  rules: {
    name: [
      {required: true, message: "机主名称不能为空", trigger: "blur"}
    ],
    UIdentity: [
      {required: true, message: "身份不能为空", trigger: "change"}
    ],
    studentId: [
      {required: true, message: "学号不能为空", trigger: "blur"}
    ],
    building: [
      {required: true, message: "宿舍栋数不能为空", trigger: "change"}
    ],
    dormitory: [
      {required: true, message: "宿舍号不能为空", trigger: "blur"}
    ],
    phone: [
      {required: true, message: "手机号不能为空", trigger: "blur"}
    ],
    type: [
      {required: true, message: "订单类型不能为空", trigger: "change"}
    ],
    details: [
      {required: true, message: "订单详情不能为空", trigger: "blur"}
    ],
    status: [
      {required: true, message: "订单状态不能为空", trigger: "change"}
    ],
    createTime: [
      {required: true, message: "创建时间不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询维修站订单列表 */
function getList() {
  loading.value = true;
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    UIdentity: null,
    studentId: null,
    building: null,
    dormitory: null,
    phone: null,
    type: null,
    details: null,
    status: null,
    staffId: null,
    createTime: null,
    updateTime: null,
    updateBy: null,
    completionTime: null,
    assignorId: null,
    remark: null,
    delFlag: null
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  console.log(queryParams)
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.status = 1
  open.value = true;
  title.value = "添加维修站订单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data;
    form.value.type = String(form.value.type)
    open.value = true;
    title.value = "修改维修站订单";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除维修站订单编号为"' + _ids + '"的数据项？').then(function () {
    return delOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 作废按钮操作 */
function handleInvalidate(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认作废维修站订单编号为"' + _ids + '"的数据项？').then(function () {
    return invalidateOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("作废成功");
  }).catch(() => {
  });
}

/** 获取订单更多信息 */
async function handleOrderDesc(row) {
  await orderState.setOrder(row)
  await router.push(`/wxz/desc/order`);
}

/** 导出已选日期操作 */
function handleExportByDate() {
  proxy.download('wxz/order/exportYiLao', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

/** 导出全部按钮操作 */
function handleExport() {
  proxy.download('wxz/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

/** 学期大清空 */
let confirmCount = 0
async function handleResetSemester () {
  const askConfirm = () => {
    proxy.$modal.confirm(`是否确认进行订单大清空？（第 ${confirmCount + 1} 次确认）`)
        .then(async () => {
          confirmCount++
          if (confirmCount < 3) {
            // 继续下一次确认
            askConfirm()
          } else {
            // 满 3 次确认，真正清空数据库
            await resetSemester()
            getList()
            proxy.$modal.msgSuccess("学期订单已清空！")
            confirmCount = 0 // 归零
          }
        })
        .catch(() => {
          proxy.$modal.msgWarning("已取消操作")
          confirmCount = 0 // 归零
        })
  }
  askConfirm()
}
/* 组件被 <keep-alive> 缓存并 再次激活（切回来） 时，会触发 */
onActivated(() => getList())

getList();
</script>

<style>
.table-details {
  font-size: 12px;
  line-height: 12px !important;
}

</style>
